package top.waikin.mooc.portal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import top.waikin.mooc.entity.CourseChapter;
import top.waikin.mooc.mapper.CourseChapterMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.waikin.mooc.portal.domain.CourseChapterDto;
import top.waikin.mooc.portal.service.CourseChapterService;
import top.waikin.mooc.portal.service.CourseService;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 课程章节 服务实现类
 */
@Service
public class CourseChapterServiceImpl extends ServiceImpl<CourseChapterMapper, CourseChapter> implements CourseChapterService {

    @Autowired
    CourseService courseService;

    @Override
    public int create(Integer courseId, CourseChapterDto courseChapterDto) {
        courseService.checkPermission(courseId);
//        CourseChapter courseChapter = new CourseChapter();
//        BeanUtil.copyProperties(courseChapterDto, courseChapter);
//        courseChapter.setCourseId(courseId);
//        // 查询它的上一章节是否存在
//        Wrapper<CourseChapter> previousWrapper = new LambdaQueryWrapper<CourseChapter>()
//                .eq(CourseChapter::getCourseId, courseId)
//                .eq(CourseChapter::getNextId, courseChapterDto.getNextId());
//        CourseChapter previous = getOne(previousWrapper);
//        if (ObjectUtil.isNull(previous)) {
//            // 不存在则作为最后一个章节
//            courseChapter.setNextId(-1);
//            // 找最后一个章节
//            previousWrapper = new LambdaQueryWrapper<CourseChapter>()
//                    .eq(CourseChapter::getCourseId, courseId)
//                    .eq(CourseChapter::getNextId, -1);
//            previous = getOne(previousWrapper);
//        }
//        save(courseChapter);
//        if (ObjectUtil.isNotNull(previous)) {
//            // 更新上一章节的nextId指向新章节id
//            previous.setNextId(courseChapter.getId());
//            updateById(previous);
//        }
//        return courseChapter.getId();
        CourseChapter toSave = new CourseChapter();
        BeanUtil.copyProperties(courseChapterDto, toSave);
        toSave.setCourseId(courseId);
        List<CourseChapter> chapterList = list(courseId);
        // 插入X、Y之间的节点
        CourseChapter Y = chapterList.stream().filter(courseChapter -> ObjectUtil.equal(courseChapter.getId(), courseChapterDto.getNextId())).findFirst().orElse(null);
        CourseChapter X = chapterList.stream().filter(courseChapter -> ObjectUtil.equal(courseChapter.getNextId(), courseChapterDto.getNextId())).findFirst().orElse(null);

        if (ObjectUtil.isNull(X) && ObjectUtil.isNull(Y)) {
            // X和Y都不存在则插入到末尾 即倒数第一个为X
            X = chapterList.stream().filter(courseChapter -> ObjectUtil.equals(courseChapter.getNextId(), -1)).findFirst().orElse(null);
            toSave.setNextId(-1);
        }
        save(toSave);
        if (ObjectUtil.isNotNull(X)) {
            X.setNextId(toSave.getId());
            updateById(X);
        }
        return toSave.getId();
    }

    @Override
    public boolean delete(Integer courseId, Integer id) {
        courseService.checkPermission(courseId);
//        // 找删除章节
//        Wrapper<CourseChapter> delWrapper = new LambdaQueryWrapper<CourseChapter>()
//                .eq(CourseChapter::getCourseId, courseId)
//                .eq(CourseChapter::getId, id);
//        CourseChapter del = getOne(delWrapper);
//        if (ObjectUtil.isNull(del)) {
//            return false;
//        }
//        removeById(del);
//        // 找前一章节
//        Wrapper<CourseChapter> updateWrapper = new LambdaQueryWrapper<CourseChapter>()
//                .eq(CourseChapter::getCourseId, courseId)
//                .eq(CourseChapter::getNextId, del.getId());
//        CourseChapter update = new CourseChapter().setNextId(del.getNextId());
//        update(update, updateWrapper);
//        return true;
        List<CourseChapter> chapterList = list(courseId);
        // 删除X、Y之间的节点
        CourseChapter toDelete = chapterList.stream().filter(courseChapter -> ObjectUtil.equal(courseChapter.getId(), id)).findFirst().orElse(null);
        if (ObjectUtil.isNull(toDelete)) {
            return false;
        }
        removeById(toDelete);
        CourseChapter X = chapterList.stream().filter(courseChapter -> ObjectUtil.equal(courseChapter.getNextId(), id)).findFirst().orElse(null);
        if (ObjectUtil.isNotNull(X)) {
            X.setNextId(toDelete.getNextId());
            updateById(X);
        }
        return true;
    }

    @Override
    public boolean update(Integer courseId, Integer id, CourseChapterDto courseChapterDto) {
        courseService.checkPermission(courseId);
        if (ObjectUtil.equal(id, courseChapterDto.getNextId())) {
            return false;
        }

        List<CourseChapter> chapterList = list(courseId);
        CourseChapter original = chapterList.stream().filter(courseChapter -> ObjectUtil.equal(courseChapter.getId(), id)).findFirst().orElse(null);
        if (ObjectUtil.isNull(original)) {
            return false;
        }

        CourseChapter update = new CourseChapter();
        BeanUtil.copyProperties(courseChapterDto, update);
        update.setId(id);
        update.setCourseId(courseId);
        if (ObjectUtil.equal(original.getNextId(),update.getNextId())){
            return updateById(update);
        }

        // 在X、Y之间插入节点
        CourseChapter Y = chapterList.stream()
                .filter(courseChapter -> ObjectUtil.equal(courseChapter.getId(), courseChapterDto.getNextId())).findFirst().orElse(null);
        CourseChapter X = chapterList.stream()
                .filter(courseChapter -> ObjectUtil.equal(courseChapter.getNextId(), courseChapterDto.getNextId())).findFirst().orElse(null);
        CourseChapter M = chapterList.stream()
                .filter(courseChapter -> ObjectUtil.equal(courseChapter.getNextId(), id)).findFirst().orElse(null);
        if (ObjectUtil.isNull(X) && ObjectUtil.isNull(Y)) {
            return false;
        }
        updateById(update);
        if (ObjectUtil.isNotNull(X)) {
            X.setNextId(id);
            updateById(X);
        }
        // 删除M N之间的节点
        if (ObjectUtil.isNotNull(M)) {
            M.setNextId(original.getNextId());
            updateById(M);
        }
        return true;
    }

    @Override
    public List<CourseChapter> sortList(Integer courseId) {
        List<CourseChapter> courseChapterList = list(courseId);
        // 从最后一个章节开始找
        int pNextId = -1;
        ArrayList<CourseChapter> courseChapterSortList = new ArrayList<>();
        while (CollUtil.isNotEmpty(courseChapterList)) {
            int finalPNextId = pNextId;
            Optional<CourseChapter> first = courseChapterList.stream()
                    .filter(courseChapter -> courseChapter.getNextId() == finalPNextId).findFirst();
            CourseChapter courseChapter = first.get();
            pNextId = courseChapter.getId();
            courseChapterSortList.add(courseChapter);
            courseChapterList.remove(courseChapter);
        }
        return CollUtil.reverse(courseChapterSortList);
    }

    private List<CourseChapter> list(Integer courseId) {
        // 获取所有章节
        Wrapper<CourseChapter> wrapper = new LambdaQueryWrapper<CourseChapter>()
                .eq(CourseChapter::getCourseId, courseId);
        return list(wrapper);
    }
}
